package cn.guetzjb.sys.controller;

import cn.guetzjb.core.constant.SysConstants;
import cn.guetzjb.core.entity.R;
import cn.guetzjb.security.utils.SecurityUtils;
import cn.guetzjb.sys.domain.SysConfig;
import cn.guetzjb.sys.service.SysConfigService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/config")
@Tag(name = "配置管理")
@RequiredArgsConstructor
public class ConfigController {

    private final SysConfigService configService;

    @GetMapping("")
    @Operation(summary = "获取系统配置(self)")
    public R getSelfConfig() {
        SysConfig sysConfig = configService.getOne(Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getUserId, SecurityUtils.getUserId()));
        if (sysConfig == null) {
            return R.ok(new SysConfig(-1, "0", "1", "1", SysConstants.THEME_COLOR, SecurityUtils.getUserId()));
        }
        return R.ok(sysConfig);
    }

    @PostMapping("/update")
    @Operation(summary = "修改配置")
    public R updateConfig(@RequestBody SysConfig sysConfig) {
        LambdaQueryWrapper<SysConfig> wrapper = Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getUserId, SecurityUtils.getUserId());
        long count = configService.count(wrapper);
        sysConfig.setUserId(SecurityUtils.getUserId());
        if (count > 0) {
            configService.update(sysConfig, wrapper);
        } else {
            configService.save(sysConfig);
        }
        return R.ok();
    }

    @PostMapping("/reset")
    @Operation(summary = "重置配置")
    public R resetConfig() {
        return R.ok(configService.update(new SysConfig(-1, "0", "1", "1", SysConstants.THEME_COLOR, SecurityUtils.getUserId()),
                Wrappers.<SysConfig>lambdaQuery().eq(SysConfig::getUserId, SecurityUtils.getUserId())));
    }
}
